package com.api.generation.util;

import cn.hutool.core.util.StrUtil;
import org.jasypt.encryption.pbe.StandardPBEByteEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 加密/解密
 * @author chaogao
 * @date 2023/7/16 22:35
 */

public class JasyptUtil {

    private static final StandardPBEByteEncryptor byteEncryptor;

    static {
        byteEncryptor = new StandardPBEByteEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword("d2FuZ3poaWt1bkB1bml0ZWNocy5jb20");
        config.setAlgorithm("PBEWithMD5AndTripleDES");
        byteEncryptor.setConfig(config);
    }

    /**
     * 解密
     *
     * @param encryptedMessage
     * @return
     */
    public static String decrypt(String encryptedMessage) {
        if (StrUtil.isEmpty(encryptedMessage)) {
            return "";
        }
        byte[] decode = Base64.getDecoder().decode(encryptedMessage);
        byte[] decrypt = byteEncryptor.decrypt(decode);
        return new String(decrypt, StandardCharsets.UTF_8);
    }

    /**
     * 加密
     *
     * @param message
     * @return
     */
    public static String encrypt(String message) {
        if (StrUtil.isEmpty(message)) {
            return "";
        }
        byte[] encrypt = byteEncryptor.encrypt(message.getBytes());
        byte[] encode = Base64.getEncoder().encodeToString(encrypt).getBytes();
        return new String(encode, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        JasyptUtil jasyptUtil = new JasyptUtil();
        //String encrypt = JasyptUtil.encrypt("Gauss123");
        String decrypt = jasyptUtil.decrypt("BcYNLgkZRfiG9e9JOED+md6YvGUSH6xZ");
       //System.out.println(encrypt);
        System.out.println(decrypt);
    }

}
